<?php

namespace App\Admin\Service\Base;


use App\Admin\Service\AbstractAdminService;
use App\Admin\Service\Traits\DestroyServiceTrait;
use App\Admin\Service\Traits\StoreServiceTrait;
use App\Admin\Service\Traits\SwitchServiceTrait;
use App\Admin\Service\Traits\UpdateServiceTrait;
use App\Common\Model\Base\Administrators;
use App\Common\Model\Base\Role;
use App\Common\Util\EasySearch;
use App\Common\Util\EasySearchMacro\GlobalSearch;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * Class AdministratorsService
 */
class AdministratorsService extends AbstractAdminService
{
    use StoreServiceTrait, UpdateServiceTrait, DestroyServiceTrait, SwitchServiceTrait;

    public function __construct()

    {
        $this->model = new Administrators();
    }

    public function beforeStore(&$data): void
    {
        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
    }

    public function beforeUpdate(&$data, $id): void
    {
        unset($data['password']);
    }

    /**
     * @return array
     * @throws \Exception
     */
    public function lists(): array
    {
        $query   = $this->model->alias('administrators')->field([
            'administrators.id',
            'administrators.name',
            'administrators.account',
            'administrators.lately_time',
            'administrators.status',
            'administrators.role_ids',
            'administrators.create_time',
        ])->where('id', '>', 1);
        $data    = EasySearch::create($query)->addMacro(GlobalSearch::class, 'administrators.name', 'administrators.account',)->getData();
        $roleIds = array_unique(array_merge(...$data['data']->column('role_ids')));
        $roleMap = Role::whereIn('id', $roleIds)->column('name', 'id');

        $data['data']->map(function ($value) use ($roleMap) {
            $value['role'] = implode(',', array_map(fn($v) => $roleMap[$v] ?? '-', $value['role_ids']));
        });

        return $data;
    }

    /**
     * 重置密码
     *
     * @param mixed $id
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function reseatPassword(mixed $id): void
    {
        $administrators           = Administrators::find($id);
        $administrators->password = password_hash('123456', PASSWORD_DEFAULT);
        $administrators->save();
    }
}
